/*
 * Copyright (c) 2011, Janni Kovacs
 * All rights reserved.
 *
 * Redistribution and use of this software in source and binary forms, with or without modification, are
 * permitted provided that the following conditions are met:
 *
 * - Redistributions of source code must retain the above
 *   copyright notice, this list of conditions and the
 *   following disclaimer.
 *
 * - Redistributions in binary form must reproduce the above
 *   copyright notice, this list of conditions and the
 *   following disclaimer in the documentation and/or other
 *   materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package de.umass.lastfm2itunes.ui;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.util.Properties;

import javax.script.ScriptException;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

import org.xml.sax.SAXException;

import de.umass.lastfm2itunes.core.Feedback;
import de.umass.lastfm2itunes.core.Lastfm2itunes;

public class MainFrame extends JFrame implements ActionListener, Feedback {

	private JTextField userTextField;
	private JButton goButton;
	private JButton resetButton;
	private Lastfm2itunes core;
	private InfiniteProgressPanel progress;

	public MainFrame(Properties p) {
		this.core = new Lastfm2itunes(this, p);
		this.progress = new InfiniteProgressPanel();
		setTitle("lastfm2itunes");

		JLabel top = new JLabel(
				"<html>This app imports your Last.fm play counts to your iTunes library.<br/><br/>"
						+ "    <b>Note:</b> Get your tags right! This app will not update the play counts of tracks "
						+ "which are tagged wrong, despite them being scrobbled with the right tags.<br/><br/>"
						+ "    <font color='red'><b>Warning:</b></font> You are encouraged to backup your iTunes library first, "
						+ "in case something goes wrong or you are not satisfied with the result.<br/>&nbsp;</html>");
		add(top, BorderLayout.NORTH);

		JPanel center = new JPanel();
		center.add(new JLabel("Last.fm username:"));
		userTextField = new JTextField(20);
		center.add(userTextField);
		add(center);

		JPanel buttons = new JPanel();
		resetButton = new JButton("Clear play count");
		resetButton.addActionListener(this);
		goButton = new JButton("Go!");
		goButton.addActionListener(this);
	//	buttons.add(resetButton);
		buttons.add(goButton);
		JPanel south = new JPanel(new BorderLayout());
		south.add(buttons);
		JLabel gotoLastfm = new JLabel(new ImageIcon(getClass().getResource("lastfm.png")));
		JLabel gotoUmass = new JLabel("<html><u>Visit Website</u></html>");
		gotoLastfm.addMouseListener(new HyperlinkListener("http://www.last.fm"));
		gotoUmass.addMouseListener(new HyperlinkListener("http://www.u-mass.de/lastfm2itunes"));
		south.add(gotoUmass, BorderLayout.WEST);
		south.add(gotoLastfm, BorderLayout.EAST);
		add(south, BorderLayout.SOUTH);

		((JComponent) getContentPane()).setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
		setSize(500, 275);
		setLocationRelativeTo(null);
		
		addWindowListener(new WindowAdapter() {

			@Override
			public void windowClosing(WindowEvent e) {
				core.stop();
				System.exit(0);
			}
		});

		setGlassPane(progress);
	}

	public void actionPerformed(ActionEvent e) {
		Object s = e.getSource();
		if (s == resetButton) {
			try {
				core.resetPlayCounts();
			} catch (ScriptException e1) {
				e1.printStackTrace();
				JOptionPane.showMessageDialog(this, "Could not reset play count on all tracks:\n" + e1.getMessage(),
						"Error", JOptionPane.ERROR_MESSAGE);
			}
		} else if (s == goButton && !progress.started) {
			setResizable(false);
			core.setUser(this.userTextField.getText());
			userTextField.requestFocusInWindow();
			progress.setText("Initilaizing...");
			progress.start();
			new Thread() {
				public void run() {
					String message = null;
					Exception e1 = null;
					try {
						core.lastfm2itunes();
					} catch (SAXException e) {
						e.printStackTrace();
						message = "Error while loading Last.fm data";
						e1 = e;
					} catch (IOException e) {
						e.printStackTrace();
						message = "Error while loading Last.fm data";
						e1 = e;
					} catch (/*Script*/Exception e) {
						e.printStackTrace();
						message = "Could not apply play count to all tracks";
						e1 = e;
					}
					progress.stop();
					setResizable(true);
					if(message != null) {
						JOptionPane.showMessageDialog(MainFrame.this, message+"\n" + e1.getMessage(),
								"Error", JOptionPane.ERROR_MESSAGE);						
					} else {
						JOptionPane.showMessageDialog(MainFrame.this, "Done!", "Finished", JOptionPane.INFORMATION_MESSAGE);
					}
					
				}
			}.start();
		}
	}

	public void processing(String s) {
		progress.setText(s);
	}
}
